package project.meetemup.view.profile;

import java.sql.SQLException;

import project.meetemup.model.Profile;
import project.meetemup.view.ActionBarActivity;
import project.meetemup.R;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.j256.ormlite.dao.Dao;

/**
 * Profile Activity. Responsible for creating a new profile or editing a existing one
 * @since 8/04/2012
 * @author João Paulo Mota
 */
@SuppressWarnings("deprecation")
public class ProfileActivity extends ActionBarActivity {
    
    private int CAMERA_REQUEST = 1;
    private ImageButton profilePicture;
    private Button saveButton;
    private EditText name;
    private Spinner genderSpinner;
    private Spinner eyeColorSpinner;
    private Spinner hairColorSpinner;
    private Profile profile;
    Dao<Profile, Long> profileDao;
    /**
     * Called when activity is created. Set up the profile to edit or an empty profile, if we are
     * creating a new one
     */
    public void onCreate(Bundle savedInstanceState) {     
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profile);
        Long profileId = new Long(-1);
    	
        /**
         * collect the profile id, search on database using a DAO
         */
        Bundle extras = getIntent().getExtras();
        if(extras != null) {
        	profileId = extras.getLong("selectedProfileId");
        } 

        try {
			profileDao = getHelper().getProfileDao();
	    	profile = profileDao.queryForId(profileId);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        fillFields();
    }
    
    private void fillFields() {
    	if (profile != null)
    	setNameField();
        setGenderField();
        setHairColorField();
        setEyeColorField();
        setPictureButtonField();
        setSaveButtonField();
	}

	/**
     * Set profile save button for creating a new profile
     * @param profile
     */
    private void setSaveButtonField() {
    	saveButton = (Button) findViewById(R.id.SaveProfileButton);
      	saveButton.setTag(profile);
      	saveButton.setOnClickListener(new View.OnClickListener() {
             public void onClick(View view) {
            	 Dao<Profile, Long> profileDao2 = null;
            	 Profile profileToSave = null;
            	 
            	 try {
					profileDao2 = getHelper().getProfileDao();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
            	 
            	 /**
            	  * if profile already exists, it is passed for save button by tag
            	  */
            	 if(view.getTag() != null)
            		 profileToSave = (Profile) view.getTag();
            	 else
            		 profileToSave = new Profile();
            	 
            	/**
            	 * set up profile fields to persist in database
            	 */
             	name = (EditText) findViewById(R.id.EditTextName);
           	 	profileToSave.setName(name.getText().toString());
            	eyeColorSpinner = (Spinner) findViewById(R.id.EyeColorSpinner);
            	profileToSave.setEyeColor(eyeColorSpinner.getSelectedItem().toString());
            	hairColorSpinner = (Spinner) findViewById(R.id.HairColorSpinner);
            	profileToSave.setHairColor(hairColorSpinner.getSelectedItem().toString());
            	genderSpinner = (Spinner) findViewById(R.id.GenderSpinner);
            	profileToSave.setHairColor(genderSpinner.getSelectedItem().toString());
            	
            	
            	 try {
            		 /**
            		  * use dao to persist profile
            		  */
    				profileDao2.createOrUpdate(profileToSave);
    			} catch (SQLException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
                 
             }

         });
		
	}


    /**
     * set up change picture button.
     * @param profile
     */
	private void setPictureButtonField() {
    	profilePicture = (ImageButton) findViewById(R.id.ImageButton01);
        profilePicture.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// in onCreate or any event where your want the user to
                // select a file
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), CAMERA_REQUEST);
			}
		});		
	}

	/**
	 * set gender color spinner in activity view
	 * @param profile
	 */
	private void setGenderField() {
		genderSpinner = (Spinner) findViewById(R.id.GenderSpinner);
        ArrayAdapter genderAdapter = ArrayAdapter.createFromResource(
                this, R.array.genders, android.R.layout.simple_spinner_item);
        genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        genderSpinner.setAdapter(genderAdapter);

        /**
         * if profile is not null, set profile gender as default in spinner
         */                
        if(profile != null)
        	genderSpinner.setSelection(genderAdapter.getPosition(profile.getGender()));
		
	}

	/**
	 * set eye color spinner in activity view
	 * @param profile
	 */
	private void setEyeColorField() {
        eyeColorSpinner = (Spinner) findViewById(R.id.EyeColorSpinner);
        ArrayAdapter eyeColorAdapter = ArrayAdapter.createFromResource(
                this, R.array.eyecolors, android.R.layout.simple_spinner_item);
        eyeColorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        eyeColorSpinner.setAdapter(eyeColorAdapter);        

        /**
         * if profile is not null, set profile eye color as default in spinner
         */        
        if(profile != null)
        	eyeColorSpinner.setSelection(eyeColorAdapter.getPosition(profile.getEyeColor()));
		
	}

	/**
	 * set hair color spinner in activity view
	 * @param profile
	 */
	private void setHairColorField() {
        hairColorSpinner = (Spinner) findViewById(R.id.HairColorSpinner);
        ArrayAdapter hairColorAdapter = ArrayAdapter.createFromResource(
                this, R.array.haircolors, android.R.layout.simple_spinner_item);
        hairColorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        hairColorSpinner.setAdapter(hairColorAdapter);     
		
        /**
         * if profile is not null, set profile hair color as default in spinner
         */
        if(profile != null)
        	hairColorSpinner.setSelection(hairColorAdapter.getPosition(profile.getHairColor()));        
	}

    /**
     * set profile name in activity view
     * @param profile
     */
	private void setNameField() {
		if(profile != null){
			name = (EditText) findViewById(R.id.EditTextName);
			name.setText(profile.getName());        		
		}
	}


	/**
	 * action to perform once the camera application returns a result.
	 * TODO this method has to receive a path to a picture and set it as the profile picture
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
        if (requestCode == CAMERA_REQUEST) {  
            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            profilePicture.setImageBitmap(photo);
        }  
    } 
    
}